﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

public partial class Pages_Public_LoanCalculator : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        //if (!IsPostBack)
        //{
        //    CalculateSummary();
        //}
    }


    protected void BindPageInfo()
    {
        Page.Title = WebUtil.GetPageTitle(h4Heading.InnerHtml);
    }


    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            LoanSummary.Visible = true;
            CalculateSummary();
        }
    }

    protected void CalculateSummary() {

        double loanAmount = 0, annualInterestRate=0, interestRate=0, monthlyPayment=0;
        int loanTermInYear = 0, reducingBalanceMethod=0, totalInstalment=0;

        double totalAmountWithInterest = 0, totalInterest = 0, yearlyPayment=0;


        loanAmount = Convert.ToDouble(txtLoanAmount.Text); // Total Loan Amount
        annualInterestRate = Convert.ToDouble(txtInterestRate.Text); // 4%, 10% per annum etc
        loanTermInYear = Convert.ToInt32(txtLoanTermInYear.Text); // 2 years, 3 years etc
        reducingBalanceMethod = Convert.ToInt32(ddlReducingBalanceMethod.SelectedValue); // 1 = Yearly, 12 = Monthly, It is basically instalment type
        totalInstalment = loanTermInYear * reducingBalanceMethod; // Loan Term or Total Loan Term, or Total Installment
        interestRate = annualInterestRate / (100 * reducingBalanceMethod); // General Interest Rate

        monthlyPayment =  Math.Round( ( loanAmount * interestRate / (1 - Math.Pow( (1 + interestRate), (-totalInstalment) ) ) ), 2 ); // EMI or Monthly Payment Formula

        totalAmountWithInterest = Math.Round( ( monthlyPayment * totalInstalment) , 2 ); // Total amount with interest
        totalInterest = totalAmountWithInterest - loanAmount; // Total Interest
        yearlyPayment = totalAmountWithInterest / loanTermInYear; // Yeary payment


        String lblPeriod = "";

        if (reducingBalanceMethod.Equals(1))
            lblPeriod = "Year";
        else
            lblPeriod = "Month";
        
        // -- Start Populate Summary -----
        sLoanAmount.Text = loanAmount.ToString();
        sLoanPeriod.Text = totalInstalment.ToString() + " " + lblPeriod;
        sInterestRate.Text = annualInterestRate.ToString() + "%";
        sEMI.Text = monthlyPayment.ToString();
        sYearlyPayment.Text = yearlyPayment.ToString();
        sTotalInterest.Text = totalInterest.ToString();
        sTotalAmountWithInterest.Text = totalAmountWithInterest.ToString();

        // -- End Populate Summary -----

        CalculateLoanAmortization(loanAmount, monthlyPayment, interestRate, annualInterestRate, lblPeriod, totalInstalment, totalInterest, totalAmountWithInterest);

    }

    private void CalculateLoanAmortization(double loanAmount, double monthlyPayment, double interestRate, double annualInterestRate, string lblPeriod, int totalInstalment , double totalInterest, double totalAmountWithInterest)
    {
        
        StringBuilder sb = new StringBuilder();

        sb.AppendFormat("<table cellpadding='3' cellspacing='3' class='GridView'>");        
        sb.AppendFormat("<tr><th>");
        sb.Append(lblPeriod);
        sb.AppendFormat("</th><th>Loan Amount Outstanding</th><th>Interest</th><th>Principal Component</th><th>Instalment Amount</th><th>Principal Balance</th></tr>");
        int row = 1;
        for(int startInstalment = 1; startInstalment <= totalInstalment; startInstalment++){

            double interestPaid = 0, principalAmount=0, newBalance=0, outstandingBalance=0;

            interestPaid = Math.Round( ( loanAmount * interestRate ), 2 );  // Interest Paid
            outstandingBalance =  Math.Round( ( loanAmount - principalAmount ), 2 ); // Outstanding total amount
            principalAmount =  Math.Round( ( monthlyPayment - interestPaid ), 2 ); // Principal Amount Balance
            
            newBalance =  Math.Round( ( loanAmount - principalAmount ), 2 ); // Adjusted Balance
            loanAmount = Math.Round(newBalance, 2); // Loan Amount Balance

            if (loanAmount < 1)
                loanAmount = 0;

            if(row%2>0)
                sb.AppendFormat("<tr class='OddRowListing'><td>");
            else
                sb.AppendFormat("<tr class='EvenRowListing'><td>");

            sb.Append(startInstalment);
            sb.AppendFormat("</td><td>");
            sb.Append( String.Format("{0:0.00}",outstandingBalance) );
            sb.AppendFormat("</td><td>");
            sb.Append( String.Format("{0:0.00}",interestPaid) );
            sb.AppendFormat("</td><td>");
            sb.Append( String.Format("{0:0.00}",principalAmount) );
            sb.AppendFormat("</td><td>");
            sb.Append( String.Format("{0:0.00}",monthlyPayment) );
            sb.AppendFormat("</td><td>");
            sb.Append( String.Format("{0:0.00}",loanAmount) );
            sb.AppendFormat("</td></tr>");
            row++;
        }

        sb.AppendFormat("</table>");
        detailsLoan.InnerHtml = sb.ToString();

    }
}